# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2023-07-29
desc: 
sample: 
"""
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.validators import UniqueValidator

from apitest.models import UserInfo, TestCaseModel


class UserInfoSerializer(serializers.ModelSerializer):
    name = serializers.CharField(min_length=2, max_length=32,
                                 error_messages={'min_length': '项目名称不能少于2位',
                                                 'max_length': '项目名称不能大于20'},
                                 validators=[UniqueValidator(queryset=UserInfo.objects.all(),message='名称不能重复')])
    is_adult = serializers.SerializerMethodField(label='是否成人', read_only=True)  #读
    password = serializers.CharField(write_only=True) #密码一般不返回 只写数据库，不返回
    class Meta:
        model = UserInfo  #定义model  save对象
        fields = '__all__'
        #fields = ('id', 'name')

    def validate(self, attr):
        print(attr)
        queryset = UserInfo.objects.filter(name=attr['name'], age=attr['age'])
        if (queryset.exists()):
            raise ValidationError({'message': '名字和年龄重复', 'data': None})
        return attr

    def get_is_adult(self, instance):
        if int(instance.age) >= 18:
            return "成年"
        return "未成年"



class TestCaseSerializer(serializers.ModelSerializer):
    # name = serializers.CharField(min_length=2,max_length=32,
    #                              error_messages={'min_length':'项目名称不能少于2位',
    #                                            'max_length':'项目名称不能大于20'},
    #                              validators=[UniqueValidator(queryset=TestCaseModel.objects.all(),message='名称不能重复')])
    name = serializers.CharField(min_length=2, max_length=32,
                                 error_messages={'min_length': '项目名称不能少于2位',
                                                 'max_length': '项目名称不能大于20'},
                                 )
    is_adult = serializers.SerializerMethodField(label='是否成人')
    # 单字段业务
    # def validate_name(self, value):
    #     print(value)
    #     queryset = TestCaseModel.objects.filter(name=value)
    #     if queryset.exists():
    #         raise ValidationError({'message': '已经注册!', 'data': None})
    #     return value

    def validate(self,attr):
        print(attr)
        queryset = TestCaseModel.objects.filter(name = attr['name'], age=attr['age'])
        if queryset.exists():
            raise ValidationError({'message': '名字和年龄重复', 'data': None})
        return attr

    def get_is_adult(self, instance):
        if instance.age >= 18:
            return "成年"
        return "未成年"
    class Meta:
        model = TestCaseModel
        fields = '__all__'
        #fields = ('id', 'name')
